package rta.datos.conexion
{
	import flash.data.SQLConnection;
	import flash.data.SQLResult;
	import flash.data.SQLStatement;
	import flash.events.SQLErrorEvent;
	import flash.events.SQLEvent;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;

	public class SesionDB
	{
		private var conn:SQLConnection;
		private var statement:SQLStatement;
		private var _callback:Function;
		
		public function SesionDB(conn:SQLConnection)
		{
			this.conn = conn;
			statement = new SQLStatement();
			statement.sqlConnection = conn;
			statement.addEventListener(SQLErrorEvent.ERROR, onSQLError);
		}
		
		public function set callback(value:Function):void
		{
			_callback = value;
		}
		
		
		private function onSQLError(event:SQLErrorEvent):void{
			Alert.show(event.text, "ERROR");
		}
		//-------------------------------------------------
		
		
		//--CREAR SESION DE SECUENCIA--------
		public function guardarSesion(idSecuencia:int, duracion:int):void{
			statement.text = "INSERT INTO sesion(id_secuencia, duracion) VALUES(@idSecuencia, @duracion)";
			statement.parameters["@idSecuencia"] = idSecuencia;
			statement.parameters["@duracion"] = duracion;
			statement.addEventListener(SQLEvent.RESULT, resultGuardarSesion);
			statement.execute();
		}
		
		private function resultGuardarSesion(event:SQLEvent):void{
			statement.removeEventListener(SQLEvent.RESULT, resultGuardarSesion);
			statement.clearParameters();
			
			statement.text = "SELECT MAX(id_sesion) id FROM sesion";
			statement.addEventListener(SQLEvent.RESULT, resultObtenerId);
			statement.execute();
		}
		
		private function resultObtenerId(event:SQLEvent):void{
			statement.removeEventListener(SQLEvent.RESULT, resultObtenerId);
			
			var result:SQLResult = statement.getResult();
			if (result != null && result.data && result.data.length > 0 && this._callback != null) {  
				this._callback(result.data[0].id);
			}
		}		
		//-------------------------------------
		
		
		//--OBTENER SESION-----------
		/*public function obtenerSonidos():void{					
			statement.text = "SELECT id_sonido id, " +
							 "nombre nombre, " +
							 "ruta_sonido rutaSonido " +
							 "FROM sonido";
			statement.addEventListener(SQLEvent.RESULT, resultObtenerSonidos);
			statement.execute();
		}
		
		private function resultObtenerSonidos(event:SQLEvent):void{
			statement.removeEventListener(SQLEvent.RESULT, resultObtenerSonidos);
			var result:SQLResult = statement.getResult();
			if (result != null && this._callback != null) {  
				this._callback(new ArrayCollection(result.data));
			}
		}*/
		//-------------------------------------
	}
}